﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Web;
using System.Text;
using System.IO;
using System.IO.Compression;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
using Microsoft.Win32;

/// <summary>
///ZipClass 的摘要说明
/// </summary>
public class ZipClass
{
    public ZipClass()
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
    }

    //压缩方法-----------------------------------------------------------------------------
    public void CompressFile(string sourceFile, string destinationFile)
    {
        // make sure the source file is there
        if (File.Exists(sourceFile) == false)
            throw new FileNotFoundException();

        // Create the streams and byte arrays needed
        byte[] buffer = null;
        FileStream sourceStream = null;
        FileStream destinationStream = null;
        GZipStream compressedStream = null;

        try
        {
            // Read the bytes from the source file into a byte array
            sourceStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read);

            // Read the source stream values into the buffer
            buffer = new byte[sourceStream.Length];
            int checkCounter = sourceStream.Read(buffer, 0, buffer.Length);

            if (checkCounter != buffer.Length)
            {
                throw new ApplicationException();
            }

            // Open the FileStream to write to
            destinationStream = new FileStream(destinationFile, FileMode.OpenOrCreate, FileAccess.Write);

            // Create a compression stream pointing to the destiantion stream
            compressedStream = new GZipStream(destinationStream, CompressionMode.Compress, true);

            // Now write the compressed data to the destination file
            compressedStream.Write(buffer, 0, buffer.Length);

        }
        catch (ApplicationException ex)
        {
            //System.Web.HttpContext.Current.Response.Write("<script language=javascript>alert('压缩文件时发生错误：" + ex.Message + "');</script>");
        }
        finally
        {
            // Make sure we allways close all streams
            if (sourceStream != null) sourceStream.Close();
            if (compressedStream != null) compressedStream.Close();
            if (destinationStream != null) destinationStream.Close();
        }
    }

    //解压-----------------------------------------------------------------------------
    public void DecompressFile(string sourceFile, string destinationFile)
    {
        // make sure the source file is there
        if (File.Exists(sourceFile) == false) throw new FileNotFoundException();

        // Create the streams and byte arrays needed
        FileStream sourceStream = null;
        FileStream destinationStream = null;
        GZipStream decompressedStream = null;
        byte[] quartetBuffer = null;

        try
        {
            // Read in the compressed source stream
            sourceStream = new FileStream(sourceFile, FileMode.Open);

            // Create a compression stream pointing to the destiantion stream
            decompressedStream = new GZipStream(sourceStream, CompressionMode.Decompress, true);

            // Read the footer to determine the length of the destiantion file
            quartetBuffer = new byte[4];
            int position = (int)sourceStream.Length - 4;
            sourceStream.Position = position;
            sourceStream.Read(quartetBuffer, 0, 4);
            sourceStream.Position = 0;
            int checkLength = BitConverter.ToInt32(quartetBuffer, 0);

            byte[] buffer = new byte[checkLength + 100];

            int offset = 0;
            int total = 0;

            // Read the compressed data into the buffer
            while (true)
            {
                int bytesRead = decompressedStream.Read(buffer, offset, 100);
                if (bytesRead == 0) break;

                offset += bytesRead;
                total += bytesRead;
            }

            // Now write everything to the destination file
            destinationStream = new FileStream(destinationFile, FileMode.Create);
            destinationStream.Write(buffer, 0, total);

            // and flush everyhting to clean out the buffer
            destinationStream.Flush();
        }
        catch (ApplicationException ex)
        {
            //   System.Web.HttpContext.Current.Response.Write("<script language=javascript>alert('解压文件时发生错误：" + ex.Message + "');</script>");
        }
        finally
        {
            // Make sure we allways close all streams
            if (sourceStream != null) sourceStream.Close();
            if (decompressedStream != null) decompressedStream.Close();
            if (destinationStream != null) destinationStream.Close();
        }

    }



    public void unCompressRAR(string unRarPatch, string rarPatch, string rarName)
    {
        string the_rar;
        RegistryKey the_Reg;
        object the_Obj;
        string the_Info;

        the_Reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe");
        the_Obj = the_Reg.GetValue("");
        the_rar = the_Obj.ToString();
        the_Reg.Close();
        //the_rar = the_rar.Substring(1, the_rar.Length - 7);

        if (Directory.Exists(unRarPatch) == false)
        {
            Directory.CreateDirectory(unRarPatch);
        }
        the_Info = "X  -o  " + rarName + " " + unRarPatch;
        ProcessStartInfo the_StartInfo = new ProcessStartInfo();
        the_StartInfo.FileName = the_rar;
        the_StartInfo.Arguments = the_Info;
        the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        the_StartInfo.WorkingDirectory = rarPatch;//获取压缩包路径

        Process the_Process = new Process();
        the_Process.StartInfo = the_StartInfo;
        the_Process.Start();
        the_Process.WaitForExit();
        the_Process.Close();


    }



    private static bool ZipFileDictory(string FolderToZip, ZipOutputStream s, string ParentFolderName)
    {
        bool res = true;
        string[] folders, filenames;
        ZipEntry entry = null;
        FileStream fs = null;
        Crc32 crc = new Crc32();

        try
        {

            //创建当前文件夹
            entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/")); //加上 “/” 才会当成是文件夹创建
            s.PutNextEntry(entry);
            s.Flush();


            //先压缩文件，再递归压缩文件夹 
            filenames = Directory.GetFiles(FolderToZip);
            foreach (string file in filenames)
            {
                //打开压缩文件
                fs = File.OpenRead(file);

                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/" + Path.GetFileName(file)));

                entry.DateTime = DateTime.Now;
                entry.Size = fs.Length;
                fs.Close();

                crc.Reset();
                crc.Update(buffer);

                entry.Crc = crc.Value;

                s.PutNextEntry(entry);

                s.Write(buffer, 0, buffer.Length);
            }
        }
        catch
        {
            res = false;
        }
        finally
        {
            if (fs != null)
            {
                fs.Close();
                fs = null;
            }
            if (entry != null)
            {
                entry = null;
            }
            GC.Collect();
            GC.Collect(1);
        }


        folders = Directory.GetDirectories(FolderToZip);
        foreach (string folder in folders)
        {
            if (!ZipFileDictory(folder, s, Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip))))
            {
                return false;
            }
        }

        return res;
    }
    /// 压缩目录
    /// 
    /// 待压缩的文件夹，全路径格式
    /// 压缩后的文件名，全路径格式
    /// 
    private static bool ZipFileDictory(string FolderToZip, string ZipedFile, String Password)
    {
        bool res;
        if (!Directory.Exists(FolderToZip))
        {
            return false;
        }

        ZipOutputStream s = new ZipOutputStream(File.Create(ZipedFile));
        s.SetLevel(6);
        s.Password = Password;

        res = ZipFileDictory(FolderToZip, s, "");

        s.Finish();
        s.Close();

        return res;
    }

    /// 压缩文件
    /// 
    /// 要进行压缩的文件名
    /// 压缩后生成的压缩文件名
    /// 
    private static bool ZipFile(string FileToZip, string ZipedFile, String Password)
    {
        //如果文件没有找到，则报错
        if (!File.Exists(FileToZip))
        {
            throw new System.IO.FileNotFoundException("指定要压缩的文件: " + FileToZip + " 不存在!");
        }
        //FileStream fs = null;
        FileStream ZipFile = null;
        ZipOutputStream ZipStream = null;
        ZipEntry ZipEntry = null;

        bool res = true;
        try
        {
            ZipFile = File.OpenRead(FileToZip);
            byte[] buffer = new byte[ZipFile.Length];
            ZipFile.Read(buffer, 0, buffer.Length);
            ZipFile.Close();

            ZipFile = File.Create(ZipedFile);
            ZipStream = new ZipOutputStream(ZipFile);
            ZipStream.Password = Password;
            ZipEntry = new ZipEntry(Path.GetFileName(FileToZip));
            ZipStream.PutNextEntry(ZipEntry);
            ZipStream.SetLevel(6);

            ZipStream.Write(buffer, 0, buffer.Length);
        }
        catch
        {
            res = false;
        }
        finally
        {
            if (ZipEntry != null)
            {
                ZipEntry = null;
            }
            if (ZipStream != null)
            {
                ZipStream.Finish();
                ZipStream.Close();
            }
            if (ZipFile != null)
            {
                ZipFile.Close();
                ZipFile = null;
            }
            GC.Collect();
            GC.Collect(1);
        }

        return res;
    }

    /// 压缩文件 和 文件夹
    /// 
    /// 待压缩的文件或文件夹，全路径格式
    /// 压缩后生成的压缩文件名，全路径格式
    /// 
    public static bool Zip(String FileToZip, String ZipedFile, String Password)
    {
        if (Directory.Exists(FileToZip))
        {
            return ZipFileDictory(FileToZip, ZipedFile, Password);
        }
        else if (File.Exists(FileToZip))
        {
            return ZipFile(FileToZip, ZipedFile, Password);
        }
        else
        {
            return false;
        }
    }

}


